package nivalsoul.kettle.plugins.util.excel;

import cn.hutool.core.lang.Console;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.Excel03SaxReader;
import cn.hutool.poi.excel.sax.Excel07SaxReader;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.google.common.collect.Lists;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 空山苦水禅人
 * @Date 2021/11/19 18:17
 */
public class HutoolExcelUtil {
    List<List<String>> result = new ArrayList<List<String>>();
    
    public List<List<String>> readExcel(String path, int sheet){
        return readExcel(new File(path), sheet);
    }

    public List<List<String>> readExcel(File file, int sheet){
        String filename = file.getName();
        if(filename.endsWith(".xls")) {
            Excel03SaxReader reader = new Excel03SaxReader(createRowHandler());
            reader.read(file, sheet);
        } else if(filename.endsWith(".xlsx")) {
            Excel07SaxReader reader = new Excel07SaxReader(createRowHandler());
            reader.read(file, sheet);
        }
        
        return result;
    }

    private RowHandler createRowHandler() {
        return new RowHandler() {
            @Override
            public void handle(int sheetIndex, int rowIndex, List<Object> rowlist) {
                List<String> row = new ArrayList<String>();
                for (int i = 0; i < rowlist.size(); i++) {
                    Object o = rowlist.get(i);
                    row.add(o==null?"":o.toString());
                }
                result.add(row);
            }
        };
    }
}
